package leetcode_1_200;

public class LeeCode_134_timeout {
    public static void main(String[] args) {
        System.out.println(canCompleteCircuit(new int[]{1, 2, 3, 4, 5}, new int[]{3, 4, 5, 1, 2}));
        System.out.println(canCompleteCircuit(new int[]{2,3,4}, new int[]{3, 4, 3}));
        System.out.println(canCompleteCircuit(new int[]{3,1,1}, new int[]{1,2,2}));
    }
    private static int canCompleteCircuit(int[] gas, int[] cost) {
        int n = gas.length;
        for (int i = 0; i < n; i++) {
//            System.out.println(i + "-------------------");
            int have = 0;
            int cos = 0;
            boolean flag = true;
            for (int j = i + 1; j < n; j++) {
                have += gas[j - 1];
                cos += cost[j - 1];
//                System.out.println(have + " " + cos);
                if (have < cos){
                    flag = false;
                    break;
                }
            }
            for (int j = 0; j < i + 1; j++) {
                if (j == 0){
                    have += gas[n - 1];
                    cos += cost[n - 1];
                }else {
                    have += gas[j - 1];
                    cos += cost[j - 1];
                }
//                System.out.println(have + " " + cos);
                if (have < cos){
                    flag = false;
                    break;
                }
            }
            if (flag)
                return i;
        }
        return -1;
    }
}
